package com.hk.area.service.impl;

import com.hk.area.service.ChAreaService;
import com.hk.base.constant.BaseConstant;
import com.hk.base.constant.BaseRedisKeys;
import com.hk.commons.redis.RedisUtil;
import com.hk.dao.area.mapper.ChAreaMapper;
import com.hk.dao.area.model.ChArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 中国省市区表(ChArea)表服务实现类
 *
 * @author cyq
 * @since 2020-04-15 09:47:11
 */
@Service("chAreaService")
public class ChAreaServiceImpl implements ChAreaService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChAreaServiceImpl.class);
    @Resource
    private ChAreaMapper mapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ChArea queryById(Long id) {
        return mapper.queryById(id);
    }

    @Override
    public void initAreas() {
        LOGGER.info("----初始化省市县----");
        redisUtil.delKey(BaseRedisKeys.BASE_AREA);
        List<ChArea> chAreas = mapper.queryAll();
        //数据level分组
        chAreas.stream().collect(Collectors.groupingBy(ChArea::getLevel)).forEach((k, v) -> {
            if (k == 1) {
                redisUtil.putHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_PROVINCE, v);
            }
            if (k == 2) {
                redisUtil.putHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_CITY, v);

            }
            if (k == 3) {
                redisUtil.putHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_COUNTY, v);

            }
        });
        LOGGER.info("----初始化省市县 结束----");

    }

    @Override
    public void getAreas() {
        List<ChArea> province = redisUtil.getHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_PROVINCE);
        List<ChArea> city = redisUtil.getHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_CITY);
        List<ChArea> country = redisUtil.getHash(BaseRedisKeys.BASE_AREA, BaseConstant.AREA_COUNTY);
        if (province == null || city == null || country == null ){
            initAreas();
        }
    }


}